<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" >

<title>每日一题20201120（147. 对链表进行插入排序） | 小克的blog</title>

<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">

<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
<link rel="shortcut icon" href="https://woodywrx.gitee.io/blog/favicon.ico?v=1615823433634">
<link rel="stylesheet" href="https://woodywrx.gitee.io/blog/styles/main.css">



<link rel="stylesheet" href="https://unpkg.com/aos@next/dist/aos.css" />
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>



    <meta name="description" content="147. 对链表进行插入排序

思路
维护一个排好序的链表，剩下的值如果比已排好的大，直接放到尾部，如果比之前小，则从链表头遍历，找到对应的位置并插入。

为了很好找到链表头，需要设置一个哑节点。

# Definition for sin..."/>
    <meta name="keywords" content="leetcode"/>
</head>
<body>

<div id="app" class="main">

    <div class="sidebar" :class="{ 'full-height': menuVisible }">
  <div class="top-container" data-aos="fade-right">
    <div class="top-header-container">
      <a class="site-title-container" href="https://woodywrx.gitee.io/blog">
        <img src="https://woodywrx.gitee.io/blog/images/avatar.png?v=1615823433634" class="site-logo">
        <h1 class="site-title">小克的blog</h1>
      </a>
      <div class="menu-btn" @click="menuVisible = !menuVisible">
        <div class="line"></div>
      </div>
    </div>
    <div>
      
        
          <a href="https://woodywrx.gitee.io/blog" class="site-nav">
            首页
          </a>
        
      
        
          <a href="https://woodywrx.gitee.io/blog/tags" class="site-nav">
            标签
          </a>
        
      
        
          <a href="https://woodywrx.gitee.io/blog/post/about" class="site-nav">
            关于
          </a>
        
      
    </div>
  </div>
  <div class="bottom-container" data-aos="flip-up" data-aos-offset="0">
    <div class="social-container">
      
        
      
        
      
        
      
        
      
        
      
    </div>
    <div class="site-description">
      欢迎来到我的小窝~这里不仅有博客，也有日记。
    </div>
    <div class="site-footer">
      wuranxu's blog | <a class="rss" href="https://woodywrx.gitee.io/blog/atom.xml" target="_blank">RSS</a>
    </div>
  </div>
</div>


    <div class="main-container">
        <div class="content-container" data-aos="fade-up">
            <div class="post-detail">
                <h2 class="post-title">每日一题20201120（147. 对链表进行插入排序）</h2>
                <div class="post-date">2020-11-20 14:42:20</div>
                
                <div class="post-content" v-pre>
                    <h4 id="147-对链表进行插入排序"><a href="https://leetcode-cn.com/problems/insertion-sort-list/">147. 对链表进行插入排序</a></h4>
<figure data-type="image" tabindex="1"><img src="https://tva1.sinaimg.cn/large/0081Kckwgy1gkvl8kkbehj30u011a79m.jpg" alt="image-20201120134633194" loading="lazy"></figure>
<h3 id="思路">思路</h3>
<pre><code>维护一个排好序的链表，剩下的值如果比已排好的大，直接放到尾部，如果比之前小，则从链表头遍历，找到对应的位置并插入。

为了很好找到链表头，需要设置一个哑节点。
</code></pre>
<pre><code class="language-Python"># Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def insertionSortList(self, head: ListNode) -&gt; ListNode:
        # 1. 如果链表为空，直接return None
        if head is None:
            return None
        # 2. 创建一个哑节点, 指向head
        pre = ListNode(0)
        pre.next = head

        # 3. sorted_data为已经排好序的数据，current为当前要排序的元素
        sorted_data = head
        current = head.next
        
        # 4. 循环的结束条件是current走到None也就是走到最后一个元素
        while current is not None:
            # 当最后一个排好序的元素的值比待排序的值小，则sorted_data后移一位
            if sorted_data.val &lt;= current.val:
                sorted_data = sorted_data.next
            else:
                # prev为头节点，为了不影响哑节点
                prev = pre
                # 找到排好序的第一个大于当前值的节点
                while prev.next.val &lt;= current.val:
                    prev = prev.next
                # 这里要注意，prev目前指向的是第一个大于当前值的节点
                # 这里sorted_data.next = current.next
                # 是因为当前值总是在sorted_data的下一位
                # 这里相当于是把当前节点撤下，挪到前面去
                sorted_data.next = current.next
                current.next = prev.next
                prev.next = current
            # 当前节点继续走，往后挪一位
            current = sorted_data.next
        # 返回哑节点的下一位即可
        return pre.next

</code></pre>
<figure data-type="image" tabindex="2"><img src="https://tva1.sinaimg.cn/large/0081Kckwgy1gkvmu38wlpj30wy0e4wfz.jpg" alt="image-20201120144152739" loading="lazy"></figure>

                </div>
                
                    <div class="tag-container">
                        
                            <a href="https://woodywrx.gitee.io/blog/vp-bY7-nD/" class="tag">
                                leetcode
                            </a>
                        
                    </div>
                

                
                    <div class="next-post">
                        <div class="next">下一篇</div>
                        <a href="https://woodywrx.gitee.io/blog/post/mei-ri-yi-ti-20201119283-yi-dong-ling/">
                            <h3 class="post-title">
                                每日一题20201119（283. 移动零）
                            </h3>
                        </a>
                    </div>
                
                
                    <span id="/blog/post/mei-ri-yi-ti-20201120147-dui-lian-biao-jin-xing-cha-ru-pai-xu/"
                          class="leancloud_visitors" data-flag-title="每日一题20201120（147. 对链表进行插入排序）">
                <em class="post-meta-item-text">阅读量 </em>
                <i class="leancloud-visitors-count">0</i>
            </span>
                
                
                    

	<div id="vcomments" style="width: 100%;max-width:1000%;padding:2.5%"></div>



                

            </div>

        </div>
    </div>
</div>

<script src="https://unpkg.com/aos@next/dist/aos.js"></script>
<script type="application/javascript">

AOS.init();

var app = new Vue({
  el: '#app',
  data: {
    menuVisible: false,
  },
})

</script>






<script src='https://cdn.jsdelivr.net/npm/valine/dist/Valine.min.js'></script>
<script>
    new Valine({
        el: '#vcomments',
        appId: 'fT8wvEVNtx1cOcCQEs7rVwnV-gzGzoHsz',
        appKey: 'xV6aDHKSkLfP7u0cBRIzpmcy',
        avatar: '',
        pageSize: 5,
        recordIp: true,
        placeholder: 'Just Go Go',
        visitor: true,
    });
</script>
<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
</body>
</html>
